package com.cy.module.dingtalk.mobility;

import com.cy.ext.plugin.route.ControllerBind;
import com.cy.model.Site;
import com.cy.model.SiteMapDevice;
import com.cy.model.User;
import com.cy.module.WebApiController;
import com.jfinal.aop.Before;
import com.jfinal.plugin.activerecord.Page;
import com.jfinal.plugin.activerecord.tx.Tx;
import org.apache.commons.lang.StringUtils;

@ControllerBind(controllerKey = "/clmp/dingtalk/mobility/site")
public class SiteController extends WebApiController {
    @Override
    public void index() {
        Site site = getModel(Site.class);
        int page = getParaToInt("pageIndex");
        int pageSize = getParaToInt("limit");
        Page<Site> sitePage = Site.dao.paginate(page, pageSize, Site.SELECT_ALL, site);
        for (Site temp : sitePage.getList()){
            temp.put("user", temp.getUser());
        }
        renderBuiPage(sitePage, 200);
    }

    @Override
    public void update() {
        String account = getPara("account");
        User user = null;
        if (StringUtils.isNotBlank(account)){
            user = User.dao.findByAccount(account);
            if (user == null){
                renderFail("账号不存在");
                return;
            }
        }

        int id = getParaToInt();
        Site tempSite = getModel(Site.class);
        Site site = Site.dao.findById(id);
        site.coverExclude(tempSite, null);
        if (user != null)
            site.setUserId(user.getUserId());
        if (site.update()) {
            renderSuccess();
        } else {
            renderFail();
        }
    }

    @Override
    public void save() {
        String account = getPara("account");
        User user = null;
        if (StringUtils.isNotBlank(account)){
            user = User.dao.findByAccount(account);
            if (user == null){
                renderFail("账号不存在");
                return;
            }
        }

        Site site = getModel(Site.class);
        if (user != null)
            site.setUserId(user.getUserId());
        if (site.save()) {
            renderSuccess();
        } else {
            renderFail();
        }
    }

    @Override
    @Before(Tx.class)
    public void delete() {
        String[] ids = getPara().split("-");
        Site.dao.deleteBatch("id", ids);
        SiteMapDevice.dao.deleteBatch("site_id", ids);
        renderSuccess();
    }

}